package daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import dao.BackMallDao;
import pojo.Book;
import pojo.College;
import utils.DruidUtils;

public class BackMallDaoImpl implements BackMallDao{

	@Override
	public ArrayList<Book> getBooks() {
		Connection conn = DruidUtils.getConnection();
		String sql = "select * from books";
		ArrayList<Book> bList = new ArrayList<Book>();
		try {
			PreparedStatement pre = conn.prepareStatement(sql);
			ResultSet res = pre.executeQuery();
			while(res.next()) {
				Book b = new Book();
				b.setBookid(res.getInt("bookid"));
				b.setStid(res.getInt("stid"));
				b.setBookName(res.getString("bookName"));
				b.setBookKind(res.getInt("bookKind"));
				b.setBookPrice(res.getFloat("bookPrice"));
				b.setExpressPrice(res.getFloat("expressPrice"));
				b.setBookAuthor(res.getString("bookAuthor"));
				b.setBookIntroduction(res.getString("bookIntroduction"));
				b.setBookMainIma(res.getString("bookMainIma"));
				bList.add(b);
			}
			res.close();
			pre.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return bList;
	}

	@Override
	public int addBook(int stid, String bookName, int bookKind, Float bookPrice, Float expressPrice, String bookAuthor,
			String bookIntroduction, String bookMainIma) {
		Connection conn = DruidUtils.getConnection();
		String sql = "insert into books values(0,?,?,?,?,?,?,?,?)";
		PreparedStatement pre = null;
		try {
			pre = conn.prepareStatement(sql);
			pre.setInt(1, stid);
			pre.setString(2, bookName);
			pre.setInt(3, bookKind);
			pre.setFloat(4, bookPrice);
			pre.setFloat(5, expressPrice);
			pre.setString(6, bookAuthor);
			pre.setString(7, bookIntroduction);
			pre.setString(8, bookMainIma);
			return pre.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				pre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public int delBook(int bookid) {
		Connection conn = DruidUtils.getConnection();
		String sql = "delete from books where bookid = ?";
		PreparedStatement pre = null;
		try {
			pre = conn.prepareStatement(sql);
			pre.setInt(1, bookid);
			return pre.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				pre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

}
